# coding:utf-8

from common.entities import Category, Product, Products
from common.htmlparser import HtmlParser
from common.utils import cstrtime


class ProductDetailsParser:
    __parser = None

    def __init__(self):
        self.__parser = HtmlParser()
        self.__parser.addrule('currency', r'<meta property="og:price:currency" content="(.*?)"')
        self.__parser.addrule('price', '<meta property="og:price:amount" content="(.*?)"')
        self.__parser.addrule('colors', r'<span class="color-name">(.*?)</span>')
        self.__parser.addrule('sizes', r'<li class="size -radio ctg-field-radio">.*?<label for=".*?" '
                                       r'class="-radio-label">(.*?)</label>')
        self.__parser.addrule('desc1_ul', r'<a href="#description-panel".*?<ul>(.*?)</ul>')
        self.__parser.addrule('desc2', r'"description".*?"(.*?)"')
        self.__parser.addrule('feature1_ul', r'<a href="#feature-care-panel".*?<ul>(.*?)</ul>')
        self.__parser.addrule('feature2', r'product-information-tab-title.*?<ul>(.*?)</ul>')
        self.__parser.addrule('li', r'<li>(.*?)</li>')
        self.__parser.addrule('img_zoomed', r'data-zoomed-src="(.*?)"')
        self.__parser.addrule('img_main1', r'data-src="(.*?)"')
        self.__parser.addrule('img_main2', r'class="product-image".*?alt=".*?".*?src="(.*?)"')

    def __del__(self):
        self.__parser = None

    def find_currency(self, src):
        currency = self.__parser.findall('currency', src)
        if len(currency) > 0:
            return currency[0]
        else:
            return None

    def find_price(self, src):
        price = self.__parser.findall('price', src)
        if len(price) > 0:
            if not price[0].endswith('.0'):
                print('the price is malformed\n' + src)
            return price[0]
        else:
            return None

    def findall_colors(self, src):
        return self.__parser.findall('colors', src)

    def findall_sizes(self, src):
        return self.__parser.findall('sizes', src)

    def findall_desc(self, src):
        ul = self.__parser.findall('desc1_ul', src)
        if len(ul) > 0:
            desc = self.__parser.findall('li', ul[0])
        else:
            desc = self.__parser.findall('desc2', src)
            if len(desc) == 0:
                desc = None
        return desc

    def findall_features(self, src):
        ul = self.__parser.findall('feature1_ul', src)
        if len(ul) > 0:
            features = self.__parser.findall('li', ul[0])
        else:
            features = self.__parser.findall('feature2', src)
            if len(features) == 0:
                features = None
        return features

    def findall_zoomed_images(self, src):
        images = self.__parser.findall('img_zoomed', src)
        for i in range(0, len(images)):
            if images[i].startswith('//assets.burberry.com/'):
                images[i] = 'https:' + images[i]
        return images

    def findall_main_images(self, src):
        images = self.__parser.findall('img_main1', src)
        if len(images) == 0:
            images = self.__parser.findall('img_main2', src)
        for i in range(0, len(images)):
            if images[i].startswith('//assets.burberry.com/'):
                images[i] = 'https:' + images[i]
        return images


class ProductUrlParser:
    __parser = None

    def __init__(self):
        self.__parser = HtmlParser()
        self.__parser.addrule('ids', r'<div class="product-title.*?\s*?<a href=".*?" data-product-id="(.*?)"')
        self.__parser.addrule('names', r'<div class="product-title.*?\s*?<a href=".*?" data-product-id=".*?".*?>(.*?)<')
        self.__parser.addrule('cats', r'<div class="product-title.*?\s*?<a href=".*?".*?data-categoryid="(.*?)"')
        self.__parser.addrule('urls', r'<div class="product-title.*?\s*?<a href="(.*?)" data-product-id="')

    def __del__(self):
        self.__parser = None

    def findall_ids(self, src):
        ids = self.__parser.findall('ids', src)
        if len(ids) > 0:
            return ids
        else:
            return None

    def findall_names(self, src):
        names = self.__parser.findall('names', src)
        if len(names) > 0:
            return names
        else:
            return None

    def findall_cats(self, src):
        cats = self.__parser.findall('cats', src)
        if len(cats) > 0:
            return cats
        else:
            return None

    def findall_urls(self, src):
        urls = self.__parser.findall('urls', src)
        if len(urls) > 0:
            return urls
        else:
            return None

    def findall_product_urls(self, src):
        urls = self.findall_urls(src)
        if urls is None:
            return
        print(urls)
        ids = self.findall_ids(src)
        names = self.findall_names(src)
        cat_ids = self.findall_cats(src)
        products = Products()
        id_idx, name_idx, catid_idx = 0, 0, 0
        id_dict, name_dict, catid_dict = dict(), dict(), dict()
        prod_id, name, cat_id = None, None, None
        for i in range(0, len(urls)):
            if ids is not None and len(ids) >= len(urls):
                while id_idx < len(ids):
                    prod_id = id_dict.get(ids[id_idx])
                    if prod_id is None:
                        prod_id = ids[id_idx]
                        id_dict[prod_id] = prod_id
                        break
                    else:
                        id_idx += 1
            if prod_id is None:
                prod_id = urls[i]
            if names is not None and len(names) >= len(urls):
                while name_idx < len(names):
                    name = name_dict.get(names[name_idx])
                    if name is None:
                        name = names[name_idx]
                        name_dict[name] = name
                        break
                    else:
                        name_idx += 1
            if cat_ids is not None and len(cat_ids) >= len(urls):
                while catid_idx < len(cat_ids):
                    cat_id = catid_dict.get(ids[catid_idx])
                    if cat_id is None:
                        cat_id = cat_ids[catid_idx]
                        catid_dict[cat_id] = cat_id
                        break
                    else:
                        catid_idx += 1
            prod = Product(prod_id, name, urls[i], cat_id)
            products.put(prod)
        return products


class CategoryUrlParser:
    __parser = None

    def __init__(self):
        self.__parser = HtmlParser()
        self.__parser.addrule('ids', r'data-categoryid="(.*?)"')
        self.__parser.addrule('titles', r'<h2 class="category-title.*?>[\n ]*(.*?)</h2>')
        self.__parser.addrule('urls', r'data-category-url="(.*?)">')

    def findall_cats(self, src, father):
        cats = [] * 0
        ids = self.__findall_ids(src)
        titles = self.__findall_titles(src)
        urls = self.__findall_urls(src)

        id_dict = dict()
        title_dict = dict()
        id_idx, title_idx = 0, 0
        if urls is not None:
            father.has_child = True
            print(urls)
            cat_id, title = None, None
            for i in range(0, len(urls)):
                if ids is not None and len(ids) >= len(urls):
                    while id_idx < len(ids):
                        cat_id = id_dict.get(ids[id_idx])
                        if cat_id is None:
                            cat_id = ids[id_idx]
                            id_dict[cat_id] = cat_id
                            break
                        else:
                            id_idx += 1
                if cat_id is None:
                    cat_id = urls[i]
                if titles is not None and len(titles) >= len(urls):
                    while title_idx < len(titles):
                        title = title_dict.get(titles[title_idx])
                        if title is None:
                            title = titles[title_idx]
                            title_dict[title] = title
                            break
                        else:
                            title_idx += 1
                cat = Category(cat_id, title, urls[i], cstrtime())
                cat.father = father.cat_id
                cat.has_child = False
                cats.append(cat)
        else:
            father.has_child = False
            print("Can not find the sub category url")
            print("The category url is " + father.cat_url)
        return cats

    def __findall_ids(self, src):
        ids = self.__parser.findall('ids', src)
        if len(ids) > 0:
            return ids
        else:
            return None

    def __findall_titles(self, src):
        titles = self.__parser.findall('titles', src)
        if len(titles) > 0:
            return titles
        else:
            return None

    def __findall_urls(self, src):
        urls = self.__parser.findall('urls', src)
        if len(urls) > 0:
            return urls
        else:
            return None


class L1CategoryUrlParser:
    _parser = HtmlParser()

    def __init__(self):
        self._parser.addrule('titles', r'<a class="l-1 wt-link" data-wt-values="WT.z_nie=taxonomy" '
                                       r'href=".*?" title="(.*?)">')
        self._parser.addrule('urls', r'<a class="l-1 wt-link" data-wt-values="WT.z_nie=taxonomy" '
                                     r'href="(.*?)" title=".*?">')

    def __del__(self):
        self._parser = None

    def findall_titles(self, src):
        titles = self._parser.findall('titles', src)
        if len(titles) > 0:
            return titles
        else:
            return None

    def findall_urls(self, src):
        urls = self._parser.findall('urls', src)
        if len(urls) > 0:
            return urls
        else:
            return None


class L2CategoryUrlParser(L1CategoryUrlParser):
    def __init__(self):
        L1CategoryUrlParser.__init__(self)
        self._parser.addrule('titles', r'<a class="l-2.*?".*? href=".*?" title="(.*?)"')
        self._parser.addrule('urls', r'<a class="l-2.*?".*? href="(.*?)" title="')


class L3CategoryUrlParser(L1CategoryUrlParser):
    def __init__(self):
        L1CategoryUrlParser.__init__(self)
        self._parser.addrule('titles', r'<a class="l-3.*? wt-link".*? href=".*?" title="(.*?)"')
        self._parser.addrule('urls', r'<a class="l-3.*? wt-link".*? href="(.*?)" title="')
